<template>
  <div id="checkerBoxChildren">
    <div class="title vux-1px-b flex flex-space-between">
      <div>{{ name }}</div>
      <div v-if="isAddAction">
        <div class="text-orange" v-if="isDel" @click="isDel = false">完成</div>
        <div class="text-orange" v-else @click="isDel = true">编辑</div>
      </div>
    </div>
    <div class="tag-container">
        <checker
          v-model="test[i]"
          type="radio"
          v-for="(item, i) in tagData.radio"
          default-item-class="check-item"
          :key="i"
          selected-item-class="check-item-selected">
          <checker-item
            v-for="(item1, index1) in item"
            :key="index1"
            @on-item-click="radioClick(item1.radio, index1)"
            :value="item1.id">
            <span>{{item1.name}}</span>
            <i class="icon icon-checked"></i>
            <i class="icon icon-minus" v-if="item1.uid && isDel" @click.stop="handleDeltag(item1.radio, index1, item1.id, 'radio', i)"></i>
          </checker-item>
        </checker>
        <checker
          v-model="tagMultipleModel"
          type="checkbox"
          default-item-class="check-item"
          selected-item-class="check-item-selected">
          <checker-item
            v-for="(item, index) in tagData.multiple"
            :key="index"
            @on-item-click="checkboxClick(index)"
            :value="item.id">
            <span>{{item.name}}</span>
            <i class="icon icon-checked"></i>
            <i class="icon icon-minus" v-if="item.uid && isDel" @click.stop="handleDeltag('', index, item.id, 'multiple', '')"></i>
          </checker-item>
          <div class="check-item" v-if="tagType && isAddAction" @click="modal = true"><i class="icon icon-plus1"></i></div>
        </checker>
    </div>
    <div v-transfer-dom>
      <x-dialog v-model="modal" class="modal">
        <div class="title">添加{{ name }}</div>
        <div class="content">
          <div class="vux-1px">
            <x-input title="" :max=10 v-model="tagAddItem.tag_name" :placeholder="'输入'+name+'(不超过10个字)'"></x-input>
          </div>
        </div>
        <div class="btn-group vux-1px-t">
          <div class="vux-1px-r" @click="modal = false">取消</div>
          <div class="text-orange" @click="onConfirm">确认</div>
        </div>
      </x-dialog>
    </div>
    <div v-transfer-dom>
      <x-dialog v-model="showWindow" class="modal">
        <div class="title">{{ windowName }}</div>
        <div class="content">
          <div class="vux-1px">
            <x-input title="" v-model="windowValue" placeholder=" "></x-input>
          </div>
        </div>
        <div class="btn-group vux-1px-t">
          <div class="vux-1px-r" @click="onCancelWindow">取消</div>
          <div class="text-orange" @click="onConfirmWindow">确认</div>
        </div>
      </x-dialog>
    </div>

    <div v-transfer-dom>
      <x-dialog v-model="showDialog">
        <div style="padding: 0.3rem 0.6rem; overflow:hidden;">
          <p style="margin-bottom: 0.2rem;">选择上门取货车型</p>
          <div style="overflow: hidden;">
            <checker
              v-model="dialogValue"
              type="radio"
              default-item-class="check-item"
              selected-item-class="check-item-selected">
              <checker-item
                v-for="item in dialogData"
                :key="item.id"
                @on-item-click="selectDialog"
                :value="item.name">
                <span>{{item.name}}</span>
                <i class="icon icon-checked"></i>
              </checker-item>
            </checker>
          </div>
          <div style="padding-top: 0.15rem;">
            <x-button type="warn" action-type="button" @click.native="onCancelWindow">取消</x-button>
          </div>
        </div>
      </x-dialog>
    </div>

  </div>
</template>
<script>
import { getTagPost, delTag } from '../../libs/fn'
import { TransferDom, XDialog } from 'vux'
export default{
  name: 'checkerBoxChildren',
  directives: {
    TransferDom
  },
  components: { XDialog },
  props: {
    modelData: [Array, Object, String],
    value: [String, Number, Object, Array],
    name: [String],
    tagType: {
      type: [String, Number]
    },
    tagValueType: [String, Number],
    tid: [String, Number],
    serverid: [String, Number],
    isAddAction: {
      type: Boolean,
      default: true
    },
    maxLength: [String, Number]
  },
  computed: {
    globalServerID() {
      return this.$store.state.serverID
    },
    cityCode() {
      return this.$store.state.cityCode
    }
  },
  data() {
    return {
      test: {},
      dialogIdx: null,
      dialogValue: '',
      dialogType: null,
      dialogData: [],
      checkIndex: null,
      radioVal: null,
      showWindow: false,
      showDialog: false,
      windowValue: '',
      windowName: '',
      isDel: false,
      modal: false,
      tagAddItem: {
        uid: this.$store.state.userInfo.uid,
        client: $config.client_type,
        device: $config.device_type,
        token: this.$store.state.userInfo.token,
        service_id: this.$store.state.serverID,
        tag_type: this.tagType,
        tag_value_type: this.tagValueType,
        tag_name: '',
        tid: '',
        tag_value: ''
      },
      tagRadioID: [],
      tagRadioName: [],
      tagRadioValue: [],
      tagRadioType: [],
      tagRadioRadio: [],
      tagMultipleID: [],
      tagMultipleName: [],
      tagMultipleValue: [],
      tagMultipleType: [],
      tagMultipleModel: [],
      tagData: {
        radio: {},
        multiple: []
      },
      tagSubData: this.value,
      isAdd: false,
    }
  },
  watch: {
    globalServerID: function (val) {
      if(val != this.serverid){
        this.inits()
      }
    },
    cityCode: function (val) {
      if(this.globalServerID == this.serverid){
        this.inits()
      }
    },
    modelData: {
      handler: function (val) {
        if(!this.isAdd){
          this.tagData.multiple = []
          this.tagData.radio = []
        }
        if(val !== null && val !== undefined && val !== '') {
          this.setTagData()
        }
      },
      deep: true
    }
  },
  methods: {
    //设置传过来的值
    setTagData() {
      let obj = {}
      this.modelData.map(item => {
        //将单选和多选的进行分组循环
        item.radio = item.radio || 1
        if(item.radio % 2){
          //单选还有分组，牛X
          if(!obj['list' + item.radio]){
            obj['list' + item.radio] = [item]
            if(!this.isAdd){
              this.test['list' + item.radio] = ''
            }
          } else {
            obj['list' + item.radio].push(item)
          }
        } else {
          this.tagData.multiple.push(item)
        }
      })
      this.tagData.radio = obj
      this.isAdd = false
    },
    //type == 2时，选择车型
    selectDialog() {
      setTimeout(() => {
        if(this.dialogType == 'radio') {
          if(this.dialogIdx == -1){
            this.tagRadioValue.push(this.dialogValue)
          } else {
            this.tagRadioValue[this.dialogIdx] = this.dialogValue
          }
        } else if(this.dialogType == 'checkbox') {
          this.tagMultipleValue.push(this.dialogValue)
        }
        this.setTagSubData()
        this.showDialog = false
        this.dialogValue = ''
      }, 150)
    },
    checkboxClick(index) {
      const {id, type, value, name} = this.tagData.multiple[index]
      const idx = this.tagMultipleID.indexOf(id)
      if(idx == -1) {
        //中间需求 整车车长最多只能选三个

        if(this.maxLength > 0 && this.serverid == 8 && this.tagMultipleID.length >= this.maxLength) {
          this.tagMultipleModel.splice(this.tagMultipleModel.length - 1, 1)
          //this.$vux.toast.text('最多只能选择' + this.maxLength + '个', 'middle')
          return
        }

        this.checkIndex = this.tagMultipleID.push(id) - 1
        this.tagMultipleName.push(name)
        this.tagMultipleType.push(type)
      } else {
        this.tagMultipleID.splice(idx, 1)
        this.tagMultipleName.splice(idx, 1)
        this.tagMultipleType.splice(idx, 1)
        this.tagMultipleValue.splice(idx, 1)
        this.setTagSubData()
        return
      }
      if(type == 4){ //弹窗
        this.$vux.confirm.show({
          title: '<i class="icon icon-gantanhao"></i>',
          content: '是否' + value[0].name,
          confirmText: '需要',
          cancelText: '不需要',
          onConfirm: () => {
            this.tagMultipleValue.push(value[0].name)
            this.setTagSubData()
          },
          onCancel: () => {
            this.tagMultipleValue.push('')
            this.setTagSubData()
          }
        })
      } else if(type == 5 || type == 6) { // 代收货款、代收运费
        this.showWindow = true
        this.dialogIdx = idx
        this.windowName = name
        this.dialogType = 'checkbox'
      } else if(type == 2) { // 车型， 上门取货
        this.dialogData = value
        setTimeout(() => {
          this.dialogIdx = idx
          this.showDialog = true
          this.dialogType = 'checkbox'
        }, 250)

      } else {
        let v = ''
        if(value) {
          v = value[0].name
        }
        this.tagMultipleValue.push(v)
        this.setTagSubData()
      }

    },
    // type == 5 6的时候
    onConfirmWindow() {
      if(this.windowValue > 0) {
        if (this.dialogType == 'radio') {
          if (this.dialogIdx == -1) {
            this.tagRadioValue.push(this.windowValue)
          } else {
            this.tagRadioValue[this.dialogIdx] = this.windowValue
          }
        } else if (this.dialogType == 'checkbox') {
          this.tagMultipleValue.push(this.windowValue)
        }
        this.windowValue = ''
        this.showWindow = false
        this.setTagSubData()
      } else {
        this.$vux.toast.text('输入错误', 'middle')
      }
    },
    onCancelWindow() {
      this.showDialog = false
      this.showWindow = false
      if (this.dialogType == 'radio') {
        this.tagRadioID.splice(this.checkIndex, 1)
        this.tagRadioRadio.splice(this.checkIndex, 1)
        this.tagRadioName.splice(this.checkIndex, 1)
        this.tagRadioType.splice(this.checkIndex, 1)
        this.tagRadioValue.splice(this.checkIndex, 1)
        this.test['list'+ this.radioVal] = ''
      } else if (this.dialogType == 'checkbox'){
        this.tagMultipleID.splice(this.checkIndex, 1)
        this.tagMultipleModel.splice(this.checkIndex, 1)
        this.tagMultipleName.splice(this.checkIndex, 1)
        this.tagMultipleType.splice(this.checkIndex, 1)
        this.tagMultipleValue.splice(this.checkIndex, 1)
      }
    },
    radioClick(radioVal, index) {
      radioVal = radioVal || 0
      const data = this.tagData.radio['list'+radioVal]
      const {name, value, type, radio, id} = data[index]
      const idx = this.tagRadioRadio.indexOf(radio)
      if(idx == -1){
        this.checkIndex = this.tagRadioID.push(id) - 1
        this.tagRadioName.push(name)
        this.tagRadioType.push(type)
        this.tagRadioRadio.push(radio)
      } else {
        this.tagRadioID[idx] = id
        this.tagRadioName[idx] = name
        this.tagRadioType[idx] = type
        this.tagRadioRadio[idx] = radio
        this.checkIndex = idx
      }
      if(type == 4){
        this.$vux.confirm.show({
          title: '<i class="icon icon-gantanhao"></i>',
          content: '是否' + value[0].name,
          confirmText: '需要',
          cancelText: '不需要',
          onConfirm: () => {
            if(idx == -1){
              this.tagRadioValue.push(value[0].name)
            } else {
              this.tagRadioValue[idx] = value[0].name
            }
            this.setTagSubData()
          },
          onCancel: () => {
            if(idx == -1){
              this.tagRadioValue.push('')
            } else {
              this.tagRadioValue[idx] = ''
            }
            this.setTagSubData()
          }
        })
      } else if(type == 1) { //代收货款 代收运费
        this.$emit('clear-children')
        setTimeout(() => {
          this.showWindow = true
          this.dialogIdx = idx
          this.windowName = name
          this.dialogType = 'radio'
          this.radioVal = radioVal
        }, 200)
      } else if(type == 7 || type == 10) { // 车型，上门取货
        this.$emit('show-children', id)
        this.setTagSubData()
      } else {
        this.$emit('clear-children')
        this.setTagSubData()
      }
    },
    //添加标签
    onConfirm() {
      if(!this.tagAddItem.tag_name) {
        this.$vux.toast.text('请输入标签名称', 'middle')
        return
      }

      this.$vux.loading.show({
        text: '添加标签中'
      })
      if(this.tid){
        this.tagAddItem.tag_value = this.tagAddItem.tag_name
        this.tagAddItem.tid = this.tid
      }
      this.$http.post($config.host + '/api/tags/add', qs.stringify(this.tagAddItem)).then((res) => {
        const {code, msg, data} = res.data
        this.$vux.loading.hide()
        if(code == 1 && data) {
          this.isAdd = true
          this.modal = false
          this.tagAddItem.tag_name = ''
          let radio = data.radio || 1
          const item = {
            id: data.id,
            name: this.tid? data.value: data.name,
            type: this.tid? 999: 7,
            value: data.value || '',
            radio,
            uid: this.$store.state.userInfo.uid
          }
          this.$emit('add-data', item)
//          if(radio % 2){
//            //单选添加到对应分组
//            if(!this.tagData.radio['list' + radio]){
//              this.$set(this.tagData.radio, 'list' + radio, [item])
//            } else {
//              this.tagData.radio['list' + radio].push(item)
//            }
//          } else {
//            this.tagData.multiple.push(item)
//          }
        } else {
          this.$vux.toast.text(msg, 'middle')
        }
      }).catch((err) => {
        this.$vux.loading.hide()
        this.$vux.toast.text($config.errMsg, 'middle')
      })
    },
    //删除
    handleDeltag(radioIndex, index, id, checkType, idx) {
      const tagData = checkType == 'radio'? this.tagData.radio['list' + radioIndex]: this.tagData.multiple
      const delItem = {
        uid: this.$store.state.userInfo.uid,
        client: $config.client_type,
        device: $config.device_type,
        token: this.$store.state.userInfo.token,
        id: tagData[index].id
      }
      delTag($config.host + '/api/tags/del', delItem, tagData, index, data => {
        let isChecked = false
        const radioIdx = this.tagRadioID.indexOf(id)
        if(checkType == 'radio' && radioIdx > -1){
          isChecked = true
          this.test[idx] = undefined
          this.tagRadioID.splice(radioIdx, 1)
          this.tagRadioName.splice(radioIdx, 1)
          this.tagRadioValue.splice(radioIdx, 1)
          this.tagRadioType.splice(radioIdx, 1)
          this.tagRadioRadio.splice(radioIdx, 1)
        }
        const mulIdx = this.tagMultipleName.indexOf(id)
        if(checkType == 'multiple' && mulIdx > -1) {
          isChecked = true
          this.tagMultipleName.splice(mulIdx, 1)
          this.tagMultipleModel.splice(mulIdx, 1)
          this.tagMultipleValue.splice(mulIdx, 1)
          this.tagMultipleType.splice(mulIdx, 1)
          this.tagMultipleID.splice(mulIdx, 1)
        }

        if(isChecked){
          this.setTagSubData()
          this.$emit('on-del')
        }
        this.$emit('on-del-data', id, isChecked)

        //checkType == 'radio'? this.$set(this.tagData.radio, 'list' + radioIndex, data): this.tagData.multiple = data


      })
    },
    //设置提交的数据
    setTagSubData() {
      let name = [], value = [], type = [], id = []
      name = name.concat(this.tagRadioName, this.tagMultipleName)
      value = value.concat(this.tagRadioValue, this.tagMultipleValue)
      type = type.concat(this.tagRadioType, this.tagMultipleType)
      id = id.concat(this.tagRadioID, this.tagMultipleID)
      this.tagSubData.name = name
      this.tagSubData.value = value
      this.tagSubData.type = type
      this.tagSubData.id = id
      this.$emit('input', this.tagSubData)
    },
    inits() {
      this.tagData.multiple = []
      this.tagData.radio = []
      this.tagMultipleName = []
      this.tagMultipleModel = []
      this.tagMultipleValue = []
      this.tagMultipleType = []
      this.tagMultipleID = []
      this.tagRadioID = []
      this.tagRadioName = []
      this.tagRadioValue = []
      this.tagRadioType = []
      this.tagRadioRadio = []
      this.setTagSubData()
    }
  }
}
</script>
